package com.cmcc.aregister.ui.activity;

import java.util.HashMap;
import java.util.Map;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.cmcc.aregister.R;
import com.cmcc.aregister.cs.constant.Arguments;
import com.cmcc.aregister.cs.constant.ConfigUtil;
import com.cmcc.aregister.cs.constant.ConfigUtilHelper;
import com.cmcc.aregister.cs.constant.GlobalSetting;
import com.cmcc.aregister.cs.database.DatabaseAdapter;
import com.cmcc.aregister.cs.http.HttpAsyncTask;
import com.cmcc.aregister.cs.model.FamilyModel;
import com.cmcc.aregister.cs.model.MemberModel;
import com.cmcc.aregister.cs.model.User;
import com.cmcc.aregister.cs.util.Utils;
import com.cmcc.aregister.ui.adapter.FamilyMemberAdapter;
import com.cmcc.aregister.ui.dialog.MemberInfoDialog;

public class NewMyServiceActivity extends ParentActivity implements
    OnItemClickListener {
    private final String TAG = "NewMyServiceActivity";
    // ------view------
    private Button homeBtn, editBtn; // bookBtn, orderBtn;
    boolean isSet = false;
    boolean isLogin = false;
    // ------parameter------
    private User user;
    private DatabaseAdapter mDatabaseAdapter;
    // private LinearLayout layout01, layout02;
    private TextView loginWarningTitle;
    private boolean canCheckOtherMsg = false;
    private ListView listView;
    private FamilyModel family;
    private MemberModel selectedMember;
    private String card_type;

    // -----------

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        init(R.layout.p_new_myservice);
        mHttpManager.setCxt(getParent());
        // showRegister();
    }

    /**
     * 判断提示注册
     */
    private void showRegister() {
        if (ConfigUtilHelper.isLogin(app)
            && ConfigUtilHelper.getUsername(app).equals("")) {
            showDoubleDlg_(getString(R.string.notice),
                getString(R.string.dialog_no_register1),
                getString(R.string.dialog_sure_register1),
                getString(R.string.dialog_back_index));
        }
    }

    @Override
    public void doPWork_() {
        super.doPWork_();
        gotoRegist();
    }

    @Override
    public void doBackIndex() {
        super.doBackIndex();
        gotoIndex();
    }

    private void gotoIndex() {
        finish();
        /*
         * Intent intent = new Intent(NewMyServiceActivity.this,
         * NewIndexActivity.class);
         * intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
         * startActivity(intent);
         */
    }

    /**
     * 去注册
     */
    private void gotoRegist() {
        Intent intent = new Intent(NewMyServiceActivity.this,
            UserRegisterActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.putExtra("mobile", ConfigUtilHelper.getMobile(app));
        startActivity(intent);
        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (operDialog != null) {
            operDialog.dismiss();
        }
    }

    @Override
    protected void onRestart() {
        super.onRestart();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void setupData() {
        mDatabaseAdapter = new DatabaseAdapter(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        canCheckOtherMsg = false;
        isLogin = ConfigUtilHelper.isLogin(this);

        showRegister();

        SharedPreferences infoVisiblePre = getSharedPreferences(
            ConfigUtilHelper.INFO_VISIBLE_PREFS, Context.MODE_PRIVATE);
        isSet = infoVisiblePre.getBoolean(ConfigUtilHelper.info_visible_set,
            false);

        if (isSet) {
            if (isLogin) {
                canCheckOtherMsg = true;
            }
        }
        else {
            mDatabaseAdapter.open_user();
            Cursor c = mDatabaseAdapter.fetchAllUserData();
            if (c != null && c.getCount() > 0) {
                canCheckOtherMsg = true;
            }
            c.close();
            mDatabaseAdapter.close_user();
        }
        if (!ConfigUtilHelper.getUsername(app).equals("")) {
            getFamily();
        }

    }

    @Override
    protected void setupView() {
        ImageView iv_title = (ImageView) findViewById(R.id.title);
        iv_title.setBackgroundResource(R.drawable.family_info_title);
        homeBtn = (Button) findViewById(R.id.top_left_image);
        homeBtn.setVisibility(View.VISIBLE);
        homeBtn.setOnClickListener(onClickListener);
        editBtn = (Button) findViewById(R.id.top_right_btn);
        editBtn.setVisibility(View.GONE);
        // bookBtn = (Button) findViewById(R.id.book_btn);
        // bookBtn.setOnClickListener(onClickListener);
        // orderBtn = (Button) findViewById(R.id.order_btn);
        // orderBtn.setOnClickListener(onClickListener);
        // layout01 = (LinearLayout) findViewById(R.id.layout_01);
        // layout02 = (LinearLayout) findViewById(R.id.layout_02);
        loginWarningTitle = (TextView) findViewById(R.id.login_warning_title);
        loginWarningTitle.setOnClickListener(onClickListener);

        listView = (ListView) findViewById(R.id.listview);

    }

    private void setListView() {
        if (family != null && family.members != null
            && family.members.size() > 0) {
            FamilyMemberAdapter adapter = new FamilyMemberAdapter(this,
                family.members);
            listView.setAdapter(adapter);
            listView.setOnItemClickListener(this);
            listView.setOnItemLongClickListener(onItemLongClickListener);
        }
    }

    private Dialog dialog;

    private void showMemberDetail() {
        if (selectedMember != null) {
            dialog = new MemberInfoDialog(this, selectedMember);
            dialog.show();
        }

    }

    private OnItemLongClickListener onItemLongClickListener = new OnItemLongClickListener() {

        @Override
        public boolean onItemLongClick(AdapterView<?> arg0, View view,
            int position, long arg3) {
            TextView relationTextView = (TextView) view
                .findViewById(R.id.member_relation);
            TextView midTextView = (TextView) view.findViewById(R.id.member_id);
            TextView cardtypeTextView = (TextView) view
                .findViewById(R.id.member_cardtype);
            card_type = cardtypeTextView.getText().toString();
            int relation = Integer.parseInt(relationTextView.getText()
                .toString());
            String mid = midTextView.getText().toString();
            boolean canDelete = relation == 1 ? false : true;
            showOperDialog(canDelete, mid, relation);
            return false;
        }

    };

    private void getSelectedMember(String mid) {
        if (family != null && family.members != null
            && family.members.size() > 0) {
            for (MemberModel memberModel : family.members) {
                if (mid.equalsIgnoreCase(memberModel.member_id)) {
                    selectedMember = memberModel;
                    break;
                }
            }
        }
    }

    private Dialog operDialog;

    private void showOperDialog(boolean canDelete, final String mid,
        final int relation) {
        LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT,
            LayoutParams.WRAP_CONTENT);
        View view = getLayoutInflater().inflate(R.layout.menber_manage_dialog,
            null);
        TextView editView = (TextView) view.findViewById(R.id.member_edit);

        editView.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                getSelectedMember(mid);
                if (relation == 1) {
                    gotoEditUserInfo(true);
                }
                else {
                    gotoEditMemberActivity();
                }
                if (operDialog != null) {
                    operDialog.dismiss();
                }
            }
        });
        TextView delView = (TextView) view.findViewById(R.id.member_delete);
        delView.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                delMember(mid);
                if (operDialog != null) {
                    operDialog.dismiss();
                }
            }
        });
        if (canDelete) {
            delView.setVisibility(View.VISIBLE);
        }
        else {
            delView.setVisibility(View.GONE);
        }
        operDialog = new Dialog(this, R.style.custom_dialog);
        operDialog.setContentView(view, params);
        operDialog.setOnDismissListener(new OnDismissListener() {

            @Override
            public void onDismiss(DialogInterface dialog) {
                selectedMember = null;
            }
        });
        operDialog.show();

    }

    @Override
    public void doSomeWork() {
        getFamily();
    }

    private String delMid = "";

    private void delMember(String mid) {
        this.delMid = mid;
        showDoubleDlg_UpdFmmily("提示", "确认删除该家庭成员吗？", "确认", "取消");

    }

    @Override
    public void doPWork_UpdFmmily() {
        showProgressDialogNew(R.string.progressing_tips);
        String params = "cid=8&token=wxcityMobileClient&mid=" + delMid;
        sendDelMemberTask = new HttpAsyncTask(HttpAsyncTask.POST,
            GlobalSetting.XML_DEL_MEMBER, Arguments.DEL_MEMBER_URL, params,
            HttpAsyncTask.CACHE_TYPE_ACTION, true);
        sendDelMemberTask.setUIHandler(sendDelMemberTaskHandler);
        mHttpManager.execute(sendDelMemberTask);
    }

    private HttpAsyncTask sendDelMemberTask;

    private Handler sendDelMemberTaskHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case HttpAsyncTask.TASK_NOTIFY_RETURN_DATA:
                dismissProgressDialog();
                if (msg.obj != null) {
                    Map<String, Object> httpMap = (Map<String, Object>) msg.obj;
                    String status = (String) httpMap.get(Arguments.XML_STATUS);
                    String message = (String) httpMap
                        .get(Arguments.XML_MESSAGE);
                    if (Integer.parseInt(status) > 0) {
                        _showInfoDialog(message,
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog,
                                    int which) {

                                }
                            });
                    }
                    else {
                        showSingleAlertDlg(getString(R.string.notice), message,
                            getString(R.string.close));

                    }
                }
                else {
                    showMsg(R.string.delete_member_error);
                }
                break;
            case HttpAsyncTask.TASK_NOTIFY_CONNECTION_FAIL:
                dismissProgressDialog();
                showSingleAlertDlg(getString(R.string.notice),
                    getString(R.string.delete_member_error),
                    getString(R.string.close));
                break;
            }
        };
    };

    private void getFamily() {
        showProgressDialog();
        String params = "cid=8&token=wxcityMobileClient&phone="
            + ConfigUtilHelper.getMobile(app);
        sendGetFamilyTask = new HttpAsyncTask(HttpAsyncTask.POST,
            GlobalSetting.XML_GET_FAMILY_INFO, Arguments.GET_FAMILY_INFO_URL,
            params, HttpAsyncTask.CACHE_TYPE_ACTION, true);
        sendGetFamilyTask.setUIHandler(sendGetFamilyTaskHandler);
        mHttpManager.execute(sendGetFamilyTask);
    }

    /** 获取家庭成员信息 */
    private HttpAsyncTask sendGetFamilyTask;

    private Handler sendGetFamilyTaskHandler = new Handler() {
        @SuppressWarnings("unchecked")
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case HttpAsyncTask.TASK_NOTIFY_RETURN_DATA:
                dismissProgressDialog();
                if (msg.obj != null) {
                    Map<String, Object> httpMap = (Map<String, Object>) msg.obj;
                    family = (FamilyModel) httpMap
                        .get(Arguments.XML_FAMILY_INFO);
                    setListView();
                }
                else {
                    // showMsg(R.string.no_register);
                    // gotoEditUserInfo(false);
                    showMsg(R.string.read_member_fail);
                }
                break;
            case HttpAsyncTask.TASK_NOTIFY_CONNECTION_FAIL:
                dismissProgressDialog();
                showSingleAlertDlg(getString(R.string.notice),
                    getString(R.string.get_family_info_err),
                    getString(R.string.close));
                break;
            }
        };
    };

    /**
     * 获取用户信息
     */
    private HttpAsyncTask sendGetUserInfoTask;

    OnClickListener onClickListener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            int id = v.getId();
            switch (id) {
            case R.id.top_left_image:
                gobackHome();
                break;
            case R.id.top_right_btn:
                if (isLogin) {
                    // 如果本地有身份证信息，说明已经注册过，否则去搜索网络，如果网络数据上有身份证则注册过否则没有注册过
                    if (ConfigUtilHelper.isRegister(NewMyServiceActivity.this)) {
                        gotoEditUserInfo(true);
                    }
                    else {
                        Map<String, String> parameterMap = new HashMap<String, String>();
                        parameterMap.put("mobile", user.mobile);
                        String changeUserInfoUrl = Utils.changeUrl(
                            Arguments.SERVER_URL_GET_USER_INFO, parameterMap);
                        sendGetUserInfoTask = new HttpAsyncTask(
                            HttpAsyncTask.GET, GlobalSetting.XML_GET_USER_INFO,
                            changeUserInfoUrl, HttpAsyncTask.CACHE_TYPE_ACTION,
                            false);
                        showProgressDialog();
                        sendGetUserInfoTask
                            .setUIHandler(sendGetUserInfoTaskHandler);
                        mHttpManager.execute(sendGetUserInfoTask);
                    }
                }
                else {
                    gotoLogin();
                }
                break;
            case R.id.book_btn:
                if (canCheckOtherMsg) {
                    gotoAppManagerActivity();
                }
                else {
                    gotoLogin();
                }
                break;
            case R.id.order_btn:
                if (canCheckOtherMsg) {
                    gotoCustomManagerActivity();
                }
                else {
                    gotoLogin();
                }
                break;
            case R.id.login_warning_title:
                if (canCheckOtherMsg) {
                    if (ConfigUtilHelper.isRegister(context)) {
                        gotoAddMemberActivity();
                    }
                    else {
                        showRegister();
                    }
                }
                else {
                    gotoLogin();
                }
                break;
            }
        }
    };

    @SuppressWarnings("unchecked")
    Handler sendGetUserInfoTaskHandler = new Handler() {
        public void handleMessage(Message msg) {
            logger.d("----------sendGetUserInfoTaskHandler----------");
            switch (msg.what) {
            case HttpAsyncTask.TASK_NOTIFY_RETURN_DATA:
                if (msg.obj != null) {
                    Map<String, Object> httpMap = (Map<String, Object>) msg.obj;
                    User user_new = (User) httpMap.get(Arguments.XML_USER);
                    if ("".equals(user_new.card)
                        || "null".equals(user_new.card)) {
                        dismissProgressDialog();
                        // showInfoDialog(R.string.no_register, true);
                        showMsg(R.string.no_register);
                        gotoEditUserInfo(false);
                    }
                    else {
                        Cursor c = mDatabaseAdapter.fetchAllUserData();
                        if (c != null) {
                            if (ConfigUtilHelper.debug) {
                                Log.i(TAG, "--user count----->" + c.getCount());
                            }
                            if (c.getCount() > 0) {
                                mDatabaseAdapter.deleteAllUserData();
                                if (user_new.sex == null
                                    || user_new.sex.equals("")) {
                                    user_new.sex = "0";
                                }
                                mDatabaseAdapter.insertUserData(user_new.name,
                                    user.mobile, user_new.birth,
                                    Integer.parseInt(user_new.sex),
                                    user_new.card, user_new.social_card,
                                    user.login_date);
                            }
                            else {
                                mDatabaseAdapter.insertUserData(user_new.name,
                                    user.mobile, user_new.birth,
                                    Integer.parseInt(user_new.sex),
                                    user_new.card, user_new.social_card,
                                    user.login_date);
                            }
                        }
                        c.close();
                        mDatabaseAdapter.close_user();
                        gotoEditUserInfo(true);
                    }
                }
                else {
                    dismissProgressDialog();
                    showMsg(R.string.no_register);
                    gotoEditUserInfo(false);
                }
                break;
            case HttpAsyncTask.TASK_NOTIFY_CONNECTION_FAIL:
                dismissProgressDialog();
                showSingleAlertDlg(getString(R.string.notice),
                    getString(R.string.load_user_info_err_and_no_edit),
                    getString(R.string.close));
                break;
            }
        }
    };

    // 回到主界面
    private void gobackHome() {
        Intent intent = new Intent(NewMyServiceActivity.this,
            NewIndexActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
        finish();
    }

    // 跳转到订单管理
    private void gotoAppManagerActivity() {
        Intent intent = new Intent(NewMyServiceActivity.this,
            AppManagerActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
    }

    // 跳转到我的收藏
    private void gotoCustomManagerActivity() {
        Intent intent = new Intent(NewMyServiceActivity.this,
            CustomManagerActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
    }

    // 跳转到成员添加
    private void gotoAddMemberActivity() {
        Intent intent = new Intent(NewMyServiceActivity.this,
            MemberEditorActivity.class);
        intent.putExtra(Arguments.MEMBER_OPER_FLAG,
            ConfigUtil.MEMBER_OPER_FLAG_ADD);
        intent.putExtra(Arguments.FAMILY_ID, family.f_id);
        intent.putExtra(Arguments.AREA_ID, family.area_id);
        intent.putExtra(Arguments.CITY_ID, family.city_id);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
    }

    private void gotoEditMemberActivity() {
        Intent intent = new Intent(NewMyServiceActivity.this,
            MemberEditorActivity.class);
        intent.putExtra(Arguments.MEMBER_MODEL, selectedMember);
        intent.putExtra(Arguments.MEMBER_OPER_FLAG,
            ConfigUtil.MEMBER_OPER_FLAG_UPD);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
    }

    // 跳转到登陆界面
    private void gotoLogin() {
        Intent intent = new Intent(NewMyServiceActivity.this,
            UserLoginActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
    }

    // 回到个人信息编辑界面
    private void gotoEditUserInfo(boolean isRegister) {
        Intent intent = new Intent(NewMyServiceActivity.this,
            PersonInfoEditor.class);
        intent.putExtra(Arguments.ACTIVITY_IS_USER, isRegister);
        intent.putExtra(Arguments.ACTIVITY_CARD_TYPE, card_type);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
        long id) {
        TextView midTextView = (TextView) view.findViewById(R.id.member_id);
        String mid = midTextView.getText().toString();
        getSelectedMember(mid);
        showMemberDetail();
    }

}